<?php
namespace App\Services;

use App\Models\Shelve;

class ShelveService
{
    /**
     * 获取 status 为 'on_shelve' 的记录数
     *
     * @return int
     */
    public function getOnShelveCount()
    {
        // 定义查询条件
        $filter = ['status' => 'on_shelve'];

        // 使用 countDocuments 方法统计符合条件的文档数量
        $count = Shelve::raw(function ($collection) use ($filter) {
            return $collection->countDocuments($filter);
        });

        return $count;
    }

    /**
     * 查询包含多条 `xcx_shelve_area` 的 `xcx_shelve`
     *
     * @param string $shelveNo
     * @return array
     */
    public function getShelveWithAreas()
    {
        $pipeline = [
            [
                '$match' => ['status' => 1]
            ],
            [
                '$lookup' => [
                    'from' => 'xcx_shelve_area',
                    'localField' => 'shelve_no',
                    'foreignField' => 'shelve_no',
                    'as' => 'areas'
                ]
            ]
        ];

        $results = Shelve::raw(function ($collection) use ($pipeline) {
            return $collection->aggregate($pipeline);
        });

        return iterator_to_array($results);
    }
}

